package droid.mapViewer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import droid.mapViewer.primitives.IPrimitive;
import android.opengl.GLSurfaceView;
import java.util.Iterator;
import java.util.List;

public class OpenGLSceneRenderer implements GLSurfaceView.Renderer {

	private List<IPrimitive> primitives;
	private float _red = 0.9f;
	private float _green = 0.2f;
	private float _blue = 0.2f;
	
	private float dx=0;
	private float dy=0;
	private float posX=0;
	private float posY=0;
	
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glLoadIdentity();
	}
	
	public void onSurfaceChanged(GL10 gl, int w, int h) {
		gl.glViewport(0, 0, w, h);
	    float ratio = (float) w / h;
	    gl.glMatrixMode(GL10.GL_PROJECTION);
	    gl.glLoadIdentity();
	    gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
	}
	
	public void onDrawFrame(GL10 gl) {
		//gl.glClearColor(_red, _green, _blue, 1.0f);
		gl.glClearColor(1f, 1f, 1f, 1f);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
	    gl.glMatrixMode(GL10.GL_MODELVIEW);
	    gl.glLoadIdentity();
	    gl.glTranslatef(posX+dx, -posY-dy, -3.0f);
	    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
	    //gl.glColor4f(1-_red, 1-_green, 1-_blue, 0);
	    buildScene(gl);
	}
	
	public void setPrimitives(List<IPrimitive> primitives) {
		this.primitives=primitives;
	}
	
	private void buildScene(GL10 gl) {
		Iterator<IPrimitive> i = primitives.iterator();
		while (i.hasNext()) 
			i.next().draw(gl);
	}
	
	public void setColor(float r, float g, float b) {
		_red = r;
		_green = g;
		_blue = b;
	}
	
	public void move(float dx, float dy) {
		this.dx=dx/15.0f;
		this.dy=dy/15.0f;
	}
	
	public void savePos(float x, float y) {
		this.posX+=x/15.0f;
		this.posY+=y/15.0f;
		dx=0;
		dy=0;
	}
}
